package org.binglan.youziyuepai.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.binglan.youziyuepai.utils.ResponseVoUtils;
import org.binglan.youziyuepai.vo.CodeEnumVo;
import org.binglan.youziyuepai.vo.ResponseVo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: @description: 获取 数据库中 code -> value，枚举类必须实现
 * @author: sanjin
 * @date: 2019/4/14 14:40
 */
@Api(tags = "code代码相关接口")
@RestController
@RequestMapping("/code")
public class CodeEnumController {

    // 枚举类所在包名
    private final String PACKAGE_NAME = "org.binglan.youziyuepai.enums.code";


    @ApiOperation(value = "获取实体枚举类型接口", notes = "获取实体枚举类型接口")
    @ApiImplicitParam(name = "entity", value = "合法值：acceptDatePatCondition(接受约拍条件)/contactType(联系方式)/costType(约拍费用类型)", required = true, paramType = "query")
    @PostMapping("/codeEnum")
    public ResponseVo getCodeEnum(String entity) {
        if (StringUtils.isBlank(entity) || entity.length() <= 1) {
            return ResponseVoUtils.error("entity 参数不是合法值");

        }

        // 需要把 entity 参数首字母大写
        char c = entity.charAt(0);
        char C = (char) (c - 32);
        String clssName = PACKAGE_NAME + "." + C + entity.substring(1) + "Enum";

        try {
            // 获取枚举类的 clazz
            Class<Enum> clazz = (Class<Enum>) Class.forName(clssName);
            List<CodeEnumVo> result = new ArrayList<>();
            // 获取枚举类列表
            List<Enum> enumList = EnumUtils.getEnumList(clazz);
            // 获取 getCode 方法
            Method getCodeMethod = clazz.getMethod("getCode");
            Method getMessageMethod = clazz.getMethod("getMessage");
            for (Enum e : enumList) {
                int code = (int) getCodeMethod.invoke(e);
                String message = (String) getMessageMethod.invoke(e);
                result.add(new CodeEnumVo(code, message));
            }
            return ResponseVoUtils.success(result);
        } catch (Exception e) {
            return ResponseVoUtils.error("entity 参数不是合法值");
        }
    }
}
